package com.portal.controller;

import com.portal.exception.Assert;
import com.portal.model.entity.BookType;
import com.portal.model.vo.CartVo;
import com.portal.result.impl.BusinessCode;
import com.portal.service.BookTypeService;
import com.portal.service.CartService;
import com.portal.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("/cart")
@Tag(name = "购物车管理")
@Slf4j
public class CartController {

    @Autowired
    private CartService cartService;
    @Autowired
    private JwtUtil jwtUtil;


    @GetMapping
    @Operation(summary = "获取购物车")
    public ResponseEntity<CartVo> getCart(@RequestHeader("Authorization") String token) {
        //1. 判断token是否为空
        Assert.error(!StringUtils.hasText(token), BusinessCode.USER_NOT_LOGGED);
        //2. 解析token,获取用户id
        String userId = jwtUtil.getValue(token, "userId");
        //3. 获取购物车，查询redis
        CartVo cartVo = cartService.getCart(Long.parseLong(userId));
        log.info("获取购物车成功：{}", cartVo);
        return ResponseEntity.ok(cartVo);
    }


    @PostMapping("/{bookId}")
    @Operation(summary = "加入购物车")
    public ResponseEntity<CartVo> addCart(@RequestHeader("Authorization") String token,@PathVariable("bookId") Long bookId) {

        Assert.error(!StringUtils.hasText(token), BusinessCode.USER_NOT_LOGGED);
        String userId = jwtUtil.getValue(token, "userId");

        // 调用service层，添加购物车
        CartVo cartVo = cartService.addCartItem(Long.parseLong(userId), bookId);

        return ResponseEntity.ok(cartVo);
    }
}











